package kjj.android.ch13.app;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidNetworkActivity extends Activity {
	private TextView tv;
	private Button btnSock;
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        btnSock = (Button)findViewById(R.id.buttonSock);
        tv = (TextView)findViewById(R.id.textViewAns);
        btnSock.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try {
					Socket socket = new Socket("162.105.85.237", 8888);
					Toast.makeText(AndroidNetworkActivity.this, 
							"Socket connected successfully.",
							Toast.LENGTH_LONG	).show();
					
					InputStream inputStream = socket.getInputStream();
					byte[] buffer = new byte[inputStream.available()];
					inputStream.read(buffer);
					
					String msg = new String(buffer);
					tv.setText(msg);
					
				} catch (UnknownHostException e) {
					// TODO: handle exception
					e.printStackTrace();
				} catch (IOException e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}
		});
    }
}